package main;

import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.border.BevelBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JSplitPane;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.JEditorPane;
import javax.swing.JTable;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import com.japisoft.sc.ScEditorKit;
import net.sf.*;
import javax.swing.JToolBar;
import javax.swing.JComboBox;

@SuppressWarnings("serial")
public class QueryFrame extends JFrame 
{
	private ScEditorKit sc;
	public BufferedReader bufferedReader; 
	public boolean isConnected = false;
	public Socket serverSocket; 
	private Client client;
	public ObjectInputStream objectInputStream;
	public PrintStream printStream; 
	public int clientCounter = 0;
	private InetAddress serverAddress;
	private JMenuItem sendQueryButton;
	private JMenuItem loadQueryFileButton;
	private JMenuItem deleteButton;
	private JEditorPane queryEditorPane;
	private JComboBox databaseComboBox;
	private JTable resultTable;
	public QueryFrame(InetAddress serverAddress , Socket serverSocket , Client client) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException 
	{
		super();
		this.serverAddress = serverAddress;
		this.serverSocket = serverSocket;
		this.client = client;
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		this.setPreferredSize(new java.awt.Dimension(481, 432));
		getContentPane().setLayout(null);
		this.setTitle("epicDBMS Client");
		this.addWindowListener(new WindowAdapter() 
		{
			public void windowClosing(WindowEvent evt) 
			{
				System.out.println("Closing window...");
				try 
				{

				} 
				catch (Throwable e) 
				{
					e.printStackTrace();
				}
			}
		});
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setBounds(100, 100, 539, 337);
		getContentPane().setLayout(new BorderLayout(0, 0));
		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.5);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		addClient();
		JScrollPane jQueryEditorScrollPane = new JScrollPane();
		splitPane.setLeftComponent(jQueryEditorScrollPane);
		jQueryEditorScrollPane.setPreferredSize(new java.awt.Dimension(215, 120));
		JLabel jQueryEditorLabel = new JLabel("Query editor");
		jQueryEditorLabel.setHorizontalAlignment(SwingConstants.CENTER);
		jQueryEditorScrollPane.setColumnHeaderView(jQueryEditorLabel);
		
		queryEditorPane = new JEditorPane();
		queryEditorPane.setText("");
		jQueryEditorScrollPane.setViewportView(queryEditorPane);
		queryEditorPane.setAutoscrolls(false);
		queryEditorPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
		queryEditorPane.setPreferredSize(new java.awt.Dimension(215, 120));
		try 
		{
			sc = new ScEditorKit();
			sc.readSyntaxColorDescriptor(System.getProperty("user.dir")	+ File.separator + "lib" + File.separator + "sql.prop");
		} 
		catch (FileNotFoundException e1) 
		{
			e1.printStackTrace();
		}
		queryEditorPane.setEditorKit(sc);
		JScrollPane scrollPanel = new JScrollPane();
		splitPane.setRightComponent(scrollPanel);
		
		resultTable = new JTable();
		scrollPanel.setViewportView(resultTable);
		
		JLabel lblNewLabel = new JLabel("New label");
		scrollPanel.setColumnHeaderView(lblNewLabel);
		
		getContentPane().add(splitPane);
		
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		getContentPane().add(toolBar, BorderLayout.NORTH);
		
		JLabel lblDatabaseList = new JLabel("Database List :");
		toolBar.add(lblDatabaseList);
		
		databaseComboBox = new JComboBox((DefaultComboBoxModel)client.readObject());
		toolBar.add(databaseComboBox);
		
		JButton btnSendquery = new JButton("Send Query");
		toolBar.add(btnSendquery);
		btnSendquery.addActionListener(new ActionListener() 
		{
			public void actionPerformed(final ActionEvent evt) 
			{
				sendQueryActionPerformed();
			}
		});
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu mnExecute = new JMenu("Task");
		menuBar.add(mnExecute);
		
		sendQueryButton = new JMenuItem("Send Query");
		mnExecute.add(getSendQueryButton());
		sendQueryButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(final ActionEvent evt) 
			{
				sendQueryActionPerformed();
			}
		});
		loadQueryFileButton = new JMenuItem("Load Query");
		mnExecute.add(loadQueryFileButton);
		loadQueryFileButton.setEnabled(false);
		loadQueryFileButton.addActionListener(new ActionListener() 
		{
					public void actionPerformed(ActionEvent evt) 
					{
						loadFile();
					}
				});
		deleteButton = new JMenuItem("Clear Query");
		mnExecute.add(deleteButton);
		deleteButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{

				queryEditorPane.setText("");
			}
		});
		deleteButton.setEnabled(false);
		this.setSize(537, 454);
		enableButtons();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	public void closeConnection() 
	{
		try 
		{
			this.bufferedReader.close();
			this.printStream.close();
			this.serverSocket.close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	private void enableButtons() 
	{
		sendQueryButton.setEnabled(true);
		loadQueryFileButton.setEnabled(true);
		deleteButton.setEnabled(true);
	}
	
	public void loadFile() 
	{
		final JFileChooser fc = new JFileChooser();
		int returnVal = fc.showOpenDialog(this);

		if (returnVal == JFileChooser.APPROVE_OPTION)
		{
			File file = fc.getSelectedFile();
			queryEditorPane.setText(loadFile(file));
		}

	}
	public String loadFile(File f)
	{

		FileReader entrada = null;
		StringBuilder str = new StringBuilder();

		try 
		{
			entrada = new FileReader(f.getPath());
			int c;
			while ((c = entrada.read()) != -1) 
			{
				str.append((char) c);
			}
		} 
		catch (IOException ex)
		{
		}

		return str.toString();
	}
	
	public void sendQueryActionPerformed()
	{
		String query = queryEditorPane.getText();
		String queryType;
		int i;
		if (query.equals("")) return;
		
		query = query.trim();
		query = query.replace("\r\n", " ");

		i = query.indexOf(" ");
		if (i!=-1) queryType = query.substring(0, i);
		else return;
		
		if (queryType.equalsIgnoreCase("INSERT"))
		{
			client.writeObject(new String("INSERT"));
			client.writeObject(new String(databaseComboBox.getSelectedItem().toString()));
			client.writeObject(query);
			JOptionPane.showMessageDialog(null, (String)client.readObject());
		}
		else if (queryType.equalsIgnoreCase("DELETE"))
		{
			client.writeObject(new String("DELETE"));
			client.writeObject(new String(databaseComboBox.getSelectedItem().toString()));
			client.writeObject(query);
			JOptionPane.showMessageDialog(null, (String)client.readObject());
		}
		else if (queryType.equalsIgnoreCase("UPDATE"))
		{
			client.writeObject(new String("UPDATE"));
			client.writeObject(new String(databaseComboBox.getSelectedItem().toString()));
			client.writeObject(query);
			JOptionPane.showMessageDialog(null, (String)client.readObject());
		}
		else if (queryType.equalsIgnoreCase("SELECT"))
		{
			client.writeObject(new String("SELECT"));
			client.writeObject(new String(databaseComboBox.getSelectedItem().toString()));
			client.writeObject(query);
			String result = (String)client.readObject();
			if (result.equalsIgnoreCase("success")) resultTable.setModel((DefaultTableModel)client.readObject());
			else JOptionPane.showMessageDialog(null, (String)client.readObject());
		}
		else 
		{
			JOptionPane.showMessageDialog(null, "Error. No type of query found.");
		}
		
		
	}
	
	public JMenuItem getSendQueryButton() 
	{
		return sendQueryButton;
	}
	@SuppressWarnings("deprecation")
	private void addClient() 
	{
		Socket clientSocket = serverSocket;

	}
}
